package util

import (
	"encoding/json"
	"fmt"
	"github.com/chanxuehong/wechat/util"
	"net/http"
	"strings"
)

type Client struct {
	HttpClient *http.Client
}



func (clt *Client) GetJSON(incompleteURL string, params map[string]string, response interface{}) (err error) {

	var paramStr string = buildquery(params)

	httpClient := clt.HttpClient

	if httpClient == nil {
		httpClient = util.DefaultHttpClient
	}


	var finalURL = ""
	if strings.Contains(incompleteURL, "?") {
		finalURL = incompleteURL + paramStr
	} else {
		finalURL = incompleteURL + "?" + paramStr
	}

	if err = httpGetJSON(httpClient, finalURL, response); err != nil {
		return
	}

	return
}

func httpGetJSON(clt *http.Client, url string, response interface{}) error {
	httpResp, err := clt.Get(url)
	if err != nil {
		return err
	}
	defer httpResp.Body.Close()

	if httpResp.StatusCode != http.StatusOK {
		return fmt.Errorf("http.Status: %s", httpResp.Status)
	}
	return json.NewDecoder(httpResp.Body).Decode(response)
}

func buildquery(params map[string]string) string {

	var paramStr string = ""
	var hasParam bool = false
	for k, v := range params {
		if len(v) > 0 {
			if hasParam {
				paramStr += "&"
			}
			paramStr += k
			paramStr += "="
			paramStr += v
			hasParam = true
		}
	}
	return paramStr
}
